package cn.edu.sdyu.ie.crs.iot;

import cn.edu.sdyu.ie.crs.client.RestHttpClient;
import cn.edu.sdyu.ie.crs.domain.Device;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class HomeAssistantService {

    private static final int DEVICE_TYPE_LIGHT = 1;
    private static final int DEVICE_TYPE_SWITCH = 2;

    private static final String HA_SERVIECE_TYPE_LIGHT = "light";
    private static final String HA_SERVIECE_TYPE_SWITCH = "switch";

    @Value("${crs.iot.ha-service-endpoint}")
    private String haServiceEndpoint;

    @Value("${crs.iot.ha-service-token}")
    private String haServiceToken;

    @Autowired
    private RestHttpClient client;

    /**
     * 通过HomeAssistant获得指定设备的状态
     * @param device
     * @return
     */
    public HaDeviceState getState(Device device) {
        String url = haServiceEndpoint + "states/" + device.getEntityId();
        String result = client.executeByGet(url, haServiceToken);

        ObjectMapper mapper = new ObjectMapper();
        HaDeviceState state = null;
        try {
            state = mapper.readValue(result, HaDeviceState.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return state;

    }

    /**
     * 通过HomeAssistant打开指定设备
     * @param device
     */
    public void turnOn(Device device) {

        if(device.getEntityId() == null || device.getDeviceType() == null) {
            log.error("缺少必要的设备参数！");
        }

        String url = haServiceEndpoint + "services/" + parseDeviceType(device) + "/turn_on";
        client.executeByPost(url, haServiceToken, device.getEntityId());
    }

    /**
     * 通过HomeAssistant关闭指定设备
     * @param device
     */
    public void turnOff(Device device) {

        if(device.getEntityId() == null || device.getDeviceType() == null) {
            log.error("缺少必要的设备参数！");
        }

        String url = haServiceEndpoint + "services/" + parseDeviceType(device) + "/turn_off";
        client.executeByPost(url, haServiceToken, device.getEntityId());
    }

    /**
     * 解析HomelandAssistant设备类型
     * @param device
     * @return
     */
    public String parseDeviceType(Device device) {
        String seviceType = "";
        switch (device.getDeviceType()) {
            case DEVICE_TYPE_LIGHT:
                seviceType = HA_SERVIECE_TYPE_LIGHT;
                break;
            case DEVICE_TYPE_SWITCH:
                seviceType = HA_SERVIECE_TYPE_SWITCH;
                break;
        }

        return seviceType;
    }
}
